#!/usr/bin/env python
# encoding: utf-8


import hashlib,time,random,decimal,json
from app import db

from app.model import Electronic
from app.model import ElectronicOutCart
from app.model import ElectronicOutOrder
from app.model import ElectronicOutOrderItem

from app.common.libs.Helper import getCurrentDate, getFormatDate

class OutOrderService():

    def __init__(self):
        pass

    def createOrder(self,user_id, items = None, params = None):
        resp = {'code': 20000, 'message': '出库订单创建成功~', 'data': {}}
        # 总价
        # price_sum = decimal.Decimal( 0.00 )

        electronic_ids = []
        for item in items:
            electronic_ids.append( int(item['electronic_id']) )

        note = params['note'] if params and 'note' in params else ''
        try:
            #为了防止并发库存出问题了，我们坐下selectfor update, 这里可以给大家演示下
            tmp_electronic_list = db.session.query( Electronic ).filter( Electronic.id.in_( electronic_ids ) )\
                .with_for_update().all()

            tmp_electrionic_stock_mapping = {}
            for tmp_item in tmp_electronic_list:
                tmp_electrionic_stock_mapping[ tmp_item.id ] = tmp_item.stock

            model_order = ElectronicOutOrder()
            model_order.order_sn = self.geneOrderSn()
            model_order.user_id = user_id
            model_order.status = 1 # 请求出库
            model_order.note = note
            model_order.updated_time = model_order.created_time = getCurrentDate()
            db.session.add( model_order )
            for item in items:
                tmp_left_stock =  tmp_electrionic_stock_mapping[ item['electronic_id'] ]

                if int( item['count'] ) > int( tmp_left_stock ):
                    raise Exception( "您添加的这个元器件:%s, 使用量太大了, 剩余：%s, 你需要:%s~~"%(item['name'], tmp_left_stock, item['count'] ) )

                tmp_ret = Electronic.query.filter_by( id = item['electronic_id'] ).update({
                    "stock":int(tmp_left_stock) - int(item['count'])
                })
                if not tmp_ret:
                    raise Exception("下单失败请重新下单")

                tmp_order_item = ElectronicOutOrderItem()
                tmp_order_item.electronic_out_order_id = model_order.id
                tmp_order_item.user_id = user_id
                tmp_order_item.count = item['count']
                tmp_order_item.electronic_id = item['electronic_id']
                tmp_order_item.note = note
                tmp_order_item.updated_time = tmp_order_item.created_time = getCurrentDate()
                db.session.add( tmp_order_item )
            db.session.commit()
            resp['data'] = {
                'id' : model_order.id,
                'order_sn' : model_order.order_sn
            }
        except Exception as e:
            db.session.rollback()
            print( e )
            resp['code'] = -1
            resp['message'] = "下单失败请重新下单"
            resp['message'] = str(e)
            return resp
        return resp

    def geneOrderSn(self):
        m = hashlib.md5()
        sn = None
        while True:
            str = "%s-%s"%( int( round( time.time() * 1000) ),random.randint( 0,9999999 ) )
            m.update(str.encode("utf-8"))
            sn = m.hexdigest()
            if not ElectronicOutOrder.query.filter_by( order_sn = sn  ).first():
                break
        return sn
